package com.lxx.modules.sys.biz.impl;

import java.security.Permission;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lxx.common.BaseServiceImpl;
import com.lxx.modules.sys.biz.ISysUserBiz;
import com.lxx.modules.sys.dao.SysUserDao;
import com.lxx.modules.sys.entity.SysPermission;
import com.lxx.modules.sys.entity.SysUser;
import com.lxx.utils.Constant;
import com.lxx.utils.MailUtils;
import com.lxx.utils.Md5Utils;
import com.lxx.vo.MenuVo;

@Service
public class SysUserBizImpl extends BaseServiceImpl<SysUser, Integer, SysUserDao> implements ISysUserBiz{

	@Autowired
	private MailUtils mailUtils;
	
	@Override
	public Integer convertId(String idStr) {
		return Integer.parseInt(idStr);
	}

	@Override
	public int delete(SysUser t) {
		t.setDelFlag(true);
		return baseMapper.updateByPrimaryKeySelective(t);
	}

	@Override
	public int updateUserRole(Integer userId, String roleIds) {
		// 先删除既有的关联，再添加
		baseMapper.batchDelUserRole(userId);
		
		for (String roleId : roleIds.split(",")) {
			baseMapper.addUserRole(userId, Integer.parseInt(roleId));
		}
		
		return 0;
	}
	
	Function<SysPermission, MenuVo> cvtFun = e -> new MenuVo(e.getId(), e.getName(), e.getUrl());

	@Override
	public List<MenuVo> queryMenus(SysUser sysUser) {
		
		List<MenuVo> menus = new ArrayList<>();
		List<SysPermission> permissions = baseMapper.queryPermission4User(sysUser.getId());
		
		// 获取一级菜单
		menus = permissions.stream()
			.filter(e -> e.getPid() == 0 && e.getType() == 0)
			.map(cvtFun)
			.collect(Collectors.toList());
		
		// 填充二级菜单
		menus.forEach(e -> {
			e.setChildren(permissions.stream()
				.filter(i -> i.getPid() == e.getId())
				.map(cvtFun)
				.collect(Collectors.toList()));
		});
		
		return menus;
	}

	@Override
	public List<SysPermission> queryUserPermissions(Integer userId) {
		return baseMapper.queryPermission4User(userId);
	}

	@Override
	public void resetPasswordAndSendLoginInfo(Integer userId) {
		SysUser user = baseMapper.selectByPrimaryKey(userId);
		user.setPassword(Md5Utils.encode(Constant.DEFAULT_PWD));
		baseMapper.updateByPrimaryKeySelective(user);
		String text = String.format("用户名: %s\n密码: %s", user.getUsername(), Constant.DEFAULT_PWD);
		mailUtils.sendMail(user.getEmail(), "用户登陆信息", text);
	}

}
